/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tabuvpr.model;

import java.util.ArrayList;
import java.util.Set;
import tabuvpr.main.Tabuparameters;

/**
 *
 * @author Shadow
 */
public class Heuristica {
    
    private static long maxExecTime = 300;
    private static int maxNodesEligible = 3;

    public Solucion obtenerSolucionInicial(ArrayList<Node> pedidos) {
        Solucion solucion = new Solucion();
        Tabuparameters.vSol.setSolucion(solucion);
        Tabuparameters.vSol.setVisible(true);
        double bestCost = Double.MAX_VALUE;
        Path bestSolution = null;
        for (int i = 0; i < Tabuparameters.getNumVehiculos(); i++) {
            Vehiculo v;
            if (i < Tabuparameters.getNumCarros()) {
                v = new Carro();
            } else {
                v = new Moto();
            }
            solucion.add(v);
            while (!v.termino()) {
                v.move(pedidos);
            }
            double currentCost = v.getRuta().getCosto();
            if (currentCost < bestCost) {
               bestCost = currentCost;
                bestSolution = v.getRuta();
            }
            Tabuparameters.vSol.update(Tabuparameters.vSol.getGraphics());
            
        }
        return solucion;
    }
    
    public Solucion getImprovement(Solucion solution){
        double mejorCosto = solution.getCost();
        
        long startTime;
        long execTime = startTime = System.currentTimeMillis();
        while (execTime - startTime <= maxExecTime) {
            double costo = solution.getCost();
            for (int i=0;i<maxNodesEligible;i++){
                for (int k = i+1; k<maxNodesEligible-1;k++){
                    Solucion new_solution = twooptswap(solution,i,k);
                    double nuevoCosto = new_solution.getCost();
                    if (nuevoCosto < mejorCosto){
                        solution = new_solution;
                    }                    
                }
            }
        }
        
        return solution;     
    }
    
    
    public Solucion twooptswap(Solucion solution,int i, int k) {
        Solucion copiaSolucion=null;
        
        for (int m = 0; m<i ; m++){
            copiaSolucion.add(solution.get(m));
        }
        
        for (int n = k; n >= i ; n--){
            copiaSolucion.add(solution.get(n));
        }
        
        for (int o = k + 1; o < solution.size(); o++){
            copiaSolucion.add(solution.get(o));
        }
        
        return copiaSolucion;       
    }
}
